﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;
using YAPACS.RisServer.Interface.Imitate;

namespace YAPACS.RisServer.Controllers;

[Authorize]
public class AdvanceSearchController(ICurrentUserOrganization currentUser,
                                     IRepository<Department, Guid> departmentRep,
                                     IRepository<ApplyDepartment, Guid> applyDeparmentRep,
                                     IRepository<ExamCategory, Guid> examCategoryRep,
                                     IRepository<ExamItem, Guid> examItemRep,
                                     IRepository<ExamBodyParty, Guid> examBodyPartRep,
                                     IRepository<DeviceType, Guid> deviceTypeRep,
                                     IRepository<Institution, Guid> institutionRep,
                                     ICommonUse _commonUse
                                     ) : AbpController
{
    private readonly ICurrentUserOrganization _currentUser = currentUser;
    private readonly IRepository<Department, Guid> _departmentRep = departmentRep;
    private readonly IRepository<ApplyDepartment, Guid> _applyDeparmentRep = applyDeparmentRep;
    private readonly IRepository<ExamCategory, Guid> _examCategoryRep = examCategoryRep;
    private readonly IRepository<ExamItem, Guid> _examItemRep = examItemRep;
    private readonly IRepository<ExamBodyParty, Guid> _examBodyPartRep = examBodyPartRep;
    private readonly IRepository<DeviceType, Guid> _deviceTypeRep = deviceTypeRep;
    private readonly IRepository<Institution, Guid> _institutionRep = institutionRep;
    private readonly ICommonUse commonUse = _commonUse;


    #region 获取设备类型下拉项
    /// <summary>
    /// 设备类型选项
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/getDeviceTypeOptions")]
    public async Task<IActionResult> GetDeviceTypeOptions()
    {
        AmisRes res = new AmisRes();
        IList<DeviceType> typeList = (await _deviceTypeRep.GetListAsync(e => e.IsActive)).OrderBy(e => e.Order).ToList();
        var deviceTypes = typeList.OrderBy(e => e.Order).ThenBy(e => e.CreationTime).Select(e => new { label = e.Name, value = e.Code }).ToList();
        deviceTypes.Insert(0, new { label = "全部", value = "全部" });
        res.Data = new
        {
            options = deviceTypes
        };

        return Json(res);
    }
    #endregion


    #region 申请科室下拉项
    /// <summary>
    /// 申请科室选项
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/getApplyDepartmentOptions")]
    public async Task<IActionResult> GetApplyDepartmentOptions()
    {
        AmisRes res = new AmisRes();
        // 申请科室 （ok）
        List<ApplyDepartment> applyDepartmentList = await _applyDeparmentRep.GetListAsync(e => e.Institution.Id == _currentUser.InstitutionId && e.IsActive);
        var applyDepartments = applyDepartmentList.OrderBy(e => e.Order).ThenBy(e => e.CreationTime).ThenBy(e => e.Name).Select(e => new { label = e.Name, value = e.Oid });
        res.Data = new
        {
            options = applyDepartments
        };
        return Json(res);
    }
    #endregion


    #region 检查类别下拉项
    /// <summary>
    /// 检查类别选项
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/getExamCategoryOptions")]
    public async Task<IActionResult> GetExamCategoryOptions()
    {
        AmisRes res = new AmisRes();
        // 检查类别
        List<ExamCategory> examCategoryList = await _examCategoryRep.GetListAsync(e => e.Department.Oid == _currentUser.DepartmentId);
        var examCategories = examCategoryList.OrderBy(e => e.Order).ThenBy(e => e.DeviceType).Select(e => new { label = e.Name, value = e.Oid });
        res.Status = 0;
        res.Msg = "success";
        res.Data = new
        {
            options = examCategories
        };
        return Json(res);
    }
    #endregion


    #region 检查设备下拉项
    /// <summary>
    /// 设备选项
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/getExamDeviceOptions")]
    public async Task<IActionResult> GetExamDeviceOptions()
    {
        var department = await _departmentRep.GetAsync(_currentUser.DepartmentId.Value);
        var devices = department.GetDevices().Select(e => new { label = e.CompoundName, value = e.Oid });
        return Json(devices);
    }
    #endregion


    #region 检查项目下拉项
    /// <summary>
    /// 检查项目选项
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/getExamItemOptions")]
    public async Task<IActionResult> GetExamItemOptions()
    {
        AmisRes res = new AmisRes();
        List<ExamItem> examItemList = await _examItemRep.GetListAsync(e => e.Department.Oid == _currentUser.DepartmentId);
        examItemList = examItemList.OrderBy(e => e.Order).ThenBy(e => e.DeviceType).Where(e => e.Parent == null).ToList();
        List<object> examItems = [];
        foreach (var item in examItemList)
        {
            List<object> children = await BuildItemTreeAsync(item);
            examItems.Add(new
            {
                Label = item.Name,
                Value = item.Oid,
                Children = children
            });
        }
        res.Data = new
        {
            options = examItems
        };
        return Ok(res);
    }

    /// <summary>
    /// 构建检查项目树
    /// </summary>
    /// <param name="examItem"></param>
    /// <returns></returns>
    public async Task<List<object>> BuildItemTreeAsync(ExamItem examItem)
    {
        List<object> tree = [];
        var children = examItem.Children;
        foreach (var item in children)
        {
            List<object> childrenArray = [];
            if (item.Children.Count > 0)
            {
                childrenArray = await BuildItemTreeAsync(item);
            }
            tree.Add(new
            {
                Label = item.Name,
                Children = childrenArray,
                Value = item.Oid
            });
        }
        return tree;
    }
    #endregion


    #region 检查部位下拉项
    /// <summary>
    /// 检查部位选项
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/getExamBodyPartOptions")]
    public async Task<IActionResult> GetExamBodyPartOptions()
    {
        AmisRes res = new AmisRes();
        List<ExamBodyParty> examBodyPartList = await _examBodyPartRep.GetListAsync(e => e.Department.Oid == _currentUser.DepartmentId);
        examBodyPartList = examBodyPartList.OrderBy(e => e.Order).ThenBy(e => e.DeviceType).Where(e => e.Parent == null).ToList();
        List<object> examBodyParties = [];
        foreach (var item in examBodyPartList)
        {
            List<object> children = await BuildBodyPartTreeAsync(item);
            examBodyParties.Add(new
            {
                Label = item.Name,
                Value = item.Oid,
                Children = children
            });
        }



        res.Data = new
        {
            options = examBodyParties
        };
        return Ok(res);
    }

    /// <summary>
    /// 构建检查部位树结构
    /// </summary>
    /// <param name="bodyParty"></param>
    /// <returns></returns>
    public async Task<List<object>> BuildBodyPartTreeAsync(ExamBodyParty bodyParty)
    {
        List<object> tree = [];
        var children = bodyParty.Children;
        foreach (var item in children)
        {
            List<object> childrenArray = [];
            if (item.Children.Count > 0)
            {
                childrenArray = await BuildBodyPartTreeAsync(item);
            }
            tree.Add(new
            {
                Label = item.Name,
                Children = childrenArray,
                Value = item.Oid
            });
        }
        return tree;
    }
    #endregion



    #region 获取医院信息
    /// <summary>
    /// 获取医院信息
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("api/advanceSearch/formInit")]
    public async Task<IActionResult> FormInit()
    {
        AmisRes res = new AmisRes();
        var currInstitution = await _institutionRep.GetAsync(_currentUser.InstitutionId.Value);
        List<Institution> list = await _institutionRep.GetListAsync();
        List<object> institutions = [];
        foreach (var item in list)
        {
            institutions.Add(new
            {
                label = item.Name,
                value = item.Code
            });
        }
        var now = Clock.Now;
        var startTime = now.Date;
        var endTime = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
        res.Data = new
        {
            institutionOptions = institutions,
            currInstitution = currInstitution.Code,
            examTimeRange = startTime.ToString("yyyy-MM-dd") + "," + endTime.ToString("yyyy-MM-dd")
        };
        return Ok(res);
    }
    #endregion
}
